<template>
  <div class="x-input">
    <input
      :v-model="inputValue"
      class="field"
      :type="type"
      :placeholder="placeholder"
      :class="{ focus: show, error: showError }"
      @input="onClick"
      @focus="onFocus"
      @blur="onBlur"
    />
  </div>
</template>
<script lang="ts" setup name="XInput">
const props = defineProps({
  value: {
    type: String,
    default: '',
  },
  type: {
    type: String,
    default: 'text',
  },
  fontSize: {
    type: Number,
    default: 12,
  },
  lineHeight: {
    type: Number,
    default: 17,
  },
  safeTop: {
    type: Number,
    default: 10,
  },
  safeBottom: {
    type: Number,
    default: 10,
  },
  placeholder: {
    type: String,
    default: '请输入内容',
  },
  error: {
    type: Boolean,
    default: null,
  }
});

const emits = defineEmits(['update:value']);

const show = ref(false);

const inputValue = computed(() => {
  return props?.value ?? '';
});

const showError = computed(() => {
  if (inputValue.value !== '') {
    return false;
  }
  if (props.error && inputValue.value === '') {
    return true;
  }
  if (typeof props.error === 'boolean') {
    return props.error;
  }
});

const onFocus = (event: Event) => {
  show.value = true;
}

const onBlur = (event: Event) => {
  show.value = false;
}

const onClick = (event: Event) => {
  const currentValue: any = (event.target as HTMLInputElement).value
  emits('update:value', currentValue);
}

</script>
<style scoped lang="scss">
.x-input {
  @apply relative w-full flex-1;

  .field {
    @include form-placeholder;
    background: $input-bg;
    color: $input-color;
    border-radius: 6px;
    outline: none;

    &:focus {
      // background-color: rgba(0, 0, 0, 0.1);
      // box-shadow: 0 0 0 0.6px rgba(72, 118, 194, 1);
    }
  }

  .field {
    @apply relative w-full;
    font-size: $form-font-size;
    // line-height: 18px;
    padding: 9px 10px;
    resize: none;
    border-radius: 6px;
    position: relative;
  }

  .error {
    box-shadow: $form-error;
  }
}
</style>
